#!/usr/bin/env bash

# you can change in here
MAKE=`which make`
MAKEFILE="${PWD}/makefile"
BUILDPATH="${PWD}/build"
TARGET_PATH=""
SRC_PATH=""

# create a build directory
[ -d ${PWD}/build ] || mkdir ${PWD}/build 

# no makefile cannot run
[ -f ${PWD}/makefile ] || exit

echo "running stl_learn test program..."

## $1  target name
## $2 build target
function compile() {
    echo "$1 compiling..."
    TARGET_NAME="$1"
    TARGET_PATH="${BUILDPATH}/${TARGET_NAME}"
    SRC_PATH="${PWD}/${TARGET_NAME}"

    echo "${MAKE} -C ${SRC_PATH} -f ${MAKEFILE} target=${TARGET_NAME} buildpath=${TARGET_PATH} ${TARGET_NAME}"
    ${MAKE} -C ${SRC_PATH} -f ${MAKEFILE} target=${TARGET_NAME} buildpath=${TARGET_PATH} ${TARGET_NAME}

    echo "compile $1 done..."
}

## $1 target name
function create() {
    echo "$1 creating..."
    P="${PWD}/$1"
    echo "create path ${P}"
    cp -r ${PWD}/00_test ${P}

    echo "create done."
}

## rm build directory
function clean() {
    echo "clean..."
    rm -rf ${BUILDPATH} */**.o
    echo "clean done."
}

function allocator() {
    echo "test allocator..."
    `which clang++` -g ${PWD}/test.cc ${PWD}/test_allocator.cc -o ${PWD}/build/test_allocator
    echo "compile done"
}

function debug() {
    echo "start debuging..."
    `which gdb` ${PWD}/build/$1
    echo "done."
}

function main() {
    case $1 in 
        build)
            TARGET=$(basename $2)
            [ ! -d "${PWD}/${TARGET}" ] && echo "can not load source file." && exit;
            compile ${TARGET}
            ;;
        test) 
            echo "test $2"
            main build $2
            echo "start running..."
            ${TARGET_PATH}
            echo ""
            echo "test $2 done";;
        create)
            [ ! $2 ] && echo "error creating, no parameter" && exit
            create $2;;
        allocator)
            allocator
            ${PWD}/build/test_allocator
            echo "test done..."
            ;;
        debug)
            if [ $2 == 'allocator' ]; then
                allocator
                debug test_allocator
            else
                main build $2
                debug ${TARGET}
            fi
            ;;
        clean)
            clean;;
        *)
            echo "error parameter.";;
    esac
}

main $@
